# -*- coding: UTF-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By


from openai import OpenAI
import json

api_key = "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"

SummarizerString = "Act as an article summarizer, extracting the outline, story plot, and background story.Result output in Chinese。\n"
SummarizerToArticleString = "根据内容大纲写出一篇有趣的文章，要求开头吸引读者眼球。结构调整：将文章的段落顺序重新排列，对主题进行重新组织，使得文章呈现出新颖的结构；内容扩展；语言润色：运用修辞手法、同义词、改变语法结构等方式，使文章的语言表达更加生动、优美；保证原创度高。保持主题一致性：在调整文章内容和结构时，要确保整篇文章的逻辑、论述和风格保持一致；文章的最小长度应为1600字。内容大纲为：\n"

class GetArticleContent:
    def __init__(self, url):
        self.url = url
        
        # 创建浏览器
        self.driver = webdriver.Chrome()
        # 配置网址
        self.driver.get(url=url)

        # 获取文章标题
        self.getArticleTitle()

        # 生成文章架构
        # self.createArticleSummarizer()

        # 关闭Driver
        self.driver.close()

    def getArticleTitle(self):
        self.title = self.driver.title.rstrip("-今日头条")
        print(self.title)
        print(self.url)
        # 根据id选择元素，返回元素的webElement对象
        if "qktoutiao.com" in self.url:
            class_name = "content"
        elif "toutiao.com" in self.url:
            class_name = "article-content"
        elif "sohu.com" in self.url:
            class_name = "article"
        elif "163.com" in self.url:
            class_name = "post_body"
        
        print(class_name)
        element = self.driver.find_element(By.CLASS_NAME, class_name)

        self.content = element.text
        print(SummarizerString)
        print(self.content)

    
    def createArticleSummarizer(self):
        data = [
            {"role": "user", "content": SummarizerString + self.content}
        ]
        client = OpenAI(api_key=api_key)

        raw_response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=data,
            # stream=True,
        )
        print(raw_response)
        chat_completion = raw_response.parse()
        print(chat_completion)
        response_headers = raw_response.headers
        print(response_headers)
        print(raw_response.choices[0].text)
                
    
        

# driver = webdriver.Chrome()
# driver.get(url)

# elem = driver.find_element_by_name("q")
# elem.clear()
# elem.send_keys("pycon")
# elem.send_keys(Keys.RETURN)
# assert "No results found." not in driver.page_source
# driver.close()

if __name__ == '__main__':
    # url = "file:////Users/biwuxia/临时/content.html"
    # 头条
    url = "https://www.toutiao.com/article/7336203765306901018/?log_from=696f48f03c4b3_1708180251077"
    # 趣头条
    url = "https://html2.qktoutiao.com/detail/2024/02/19/1699883722.html?content_id=1699883722"
    # 搜话
    # url = "https://www.sohu.com/a/758716102_119778?scm="
    # 网易号
    url = "https://www.163.com/dy/article/IRB5S4GL0556123R.html"
    article =  GetArticleContent(url=url)
    